
package com.gooluke.mybatis.registar;

import com.gooluke.mybatis.annotation.Mapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.util.ClassUtils;
import org.springframework.util.StringUtils;

import java.util.Arrays;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;

@Slf4j
public class MyInterfaceScannerRegistrar implements ImportBeanDefinitionRegistrar {

    @Override
    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
        // 获取@MyInterfaceScan注解的属性
        Set<String> basePackages = getBasePackages(importingClassMetadata);

        // 创建自定义扫描器
        MyInterfaceScanner scanner = new MyInterfaceScanner(registry);

        // 扫描接口
        scanner.doScan(StringUtils.toStringArray(basePackages));
    }

    private Set<String> getBasePackages(AnnotationMetadata importingClassMetadata) {
        Map<String, Object> attributes = importingClassMetadata
                .getAnnotationAttributes(Mapper.class.getCanonicalName());

        String[] basePackagesPath = (String[]) attributes.get("basePackages");
        log.info("扫描包路径：{}", basePackagesPath);
        // 添加显式指定的包
        Set<String> basePackages = new LinkedHashSet<>(Arrays.asList(basePackagesPath));

        // 如果没指定包，则使用启动类所在包
        if (basePackages.isEmpty()) {
            log.info("未指定包，使用启动类所在包");
            basePackages.add(ClassUtils.getPackageName(importingClassMetadata.getClassName()));
        }
        return basePackages;
    }
}